<template>
    <basic-container>
        <avue-crud :option="option" :data="data" ref="crud" v-model="form" :table-loading="loading"
                   :permission="permissionList"
                   :page="page" @refresh-change="refreshChange" @search-change="searchChange"
                   @search-reset="searchReset" @current-change="currentChange"
                   @size-change="sizeChange" @on-load="onLoad" @row-del="rowDel">
            <template slot-scope="{row}" slot="menuLeft" v-if="activeName=='first'">
                <el-button type="primary" size="mini" @click="handleAdd" v-has="'/mall-cloud-advert/poster/addItem'">
                    新增
                </el-button>
            </template>
            <!-- 自定义添加搜索条件  按日期搜索  -->
            <template slot="search">
                <el-col :md="16" :xs="24">
                    <el-form-item label="有效期">
                        <el-date-picker text="有效期" v-model="acTime" type="daterange" range-separator="至" size="mini"
                                        start-placeholder="开始日期" end-placeholder="结束日期" align="right"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </template>
            <template slot-scope="scope" slot="menu">
                <el-button v-if="userId==scope.row.adUserId" type="text" size="small" icon="el-icon-edit"
                           @click="editFn(scope.row)" v-has="'/mall-cloud-advert/poster/editItem'">编辑
                </el-button>
                <el-button type="text" size="small" icon="el-icon-edit" @click="handleEdit(scope.row)">
                    查看
                </el-button>
            </template>
            <template slot-scope="{row}" slot="adStatus">
                <avue-switch @change="rowSwitchChangeStatus(row)" v-model="row.adStatus" active-color="#13ce66" inactive-color="#ff4949" :dic="dic"></avue-switch>
            </template>
            <template slot-scope="{row}" slot="adAccUrl">
                <!--                <div>-->
                <el-input :value="row.adAccUrl"></el-input>
                <el-image :src="row.adAccUrl"></el-image>
                <!--                </div>-->
            </template>
        </avue-crud>
        <!-- 新增 -->
        <el-dialog :close-on-click-modal="false" :title="titleBan" :visible.sync="dialogVisible" width="60%"
                   :before-close="closeDialog">
            <el-form :model="addForm" :rules="addrules" ref="addForm" label-width="140px" :validate-on-rule-change="true">
                <el-form-item v-if="!userRole" label="选择项目可见范围" prop="goodsClassIdsLabel">
                    <el-tooltip class="item" effect="dark" content="有区域数据时,区域选择为'[]'代表物业集团,但仍建议您重新选择区域" placement="top-start">
                    <el-select
                            v-model="addForm.goodsClassIdsLabel"
                            size="mini"
                            placeholder="请选择"
                            multiple
                            collapse-tags
                            value-key="name"
                            :disabled="isView"
                            popper-class="select"
                            @remove-tag="goodsClassRemove"
                    >
                        <el-option :value="goodsClassIdsValue" style="height: auto">
                            <el-tree
                                    :data="goodsClassIdsOptions"
                                    :default-expanded-keys="[]"
                                    node-key="id"
                                    accordion
                                    ref="goodsClassTree"
                                    highlight-current
                                    :props="propsClass"
                                    @node-click="signHandleCheckChange"
                            ></el-tree>
                        </el-option>
                    </el-select>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="广告名称" prop="adTitle">
                    <el-input :disabled="isView" v-model="addForm.adTitle" size="mini"></el-input>
                </el-form-item>
                <el-form-item label="广告位" prop="adApId">
                    <el-select :disabled="isView||isApView" v-model="addForm.adApId" placeholder="请选择所属广告位"
                               @change="getPosData" size="mini">
                        <el-option v-for="(item,index) in posData" :key="index" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="标记" prop="mark">
                    <el-radio-group v-model="addForm.mark">
                        <!--                        <el-radio disabled label='1'>电脑</el-radio>-->
                        <el-radio disabled label='2'>手机</el-radio>
                    </el-radio-group>
                </el-form-item>
                <div class="adType">
                    <el-form-item label="广告类型" prop="adType">
                        <el-select v-model="addForm.adTypeName" filterable :disabled="isView" placeholder="请选择广告类型" @change="getAdType" size="mini">
                            <el-option v-for="item in typeData" :key="item.value" :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="addForm.adType == 1" label="选择商品" prop="selectGoods">
                        <el-select placeholder="请选择商品"
                                   filterable
                                   remote
                                   :disabled="isView"
                                   @visible-change="getSelectList"
                                   @change="getlist"
                                   :remote-method="getSelectList" v-model="valueid" popper-class="selectJob" size="mini">
                            <el-option v-for="item in restoreTable" :key="item.id" :label="item.goodsName"
                                       :value="item.id">
                                <span style="float: left;width:120px"
                                      :title="item.goodsName">{{ item.goodsName }}</span>
                            </el-option>
                            <div style="text-align:center">
                                <span class="text" v-show="selectPage!=1" @click.stop="prevePage">上一页</span>
                                <span class="text" style="padding-left: 30px;" @click.stop="nextPage"
                                      v-show="selectPage !=pageCount">
									下一页
								</span>
                            </div>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="addForm.adType == 2" label="选择店铺" prop="selectStore">
                        <el-select placeholder="请选择店铺"
                                   filterable
                                   remote
                                   @visible-change="getSelectList"
                                   @change="getlist"
                                   :disabled="isView"
                                   :remote-method="getSelectList" v-model="valueid" popper-class="selectJob" size="mini">
                            <el-option v-for="item in restoreTable" :key="item.id" :label="item.storeName"
                                       :value="item.id">
                                <span style="float: left;width:120px"
                                      :title="item.storeName">{{ item.storeName }}</span>
                            </el-option>
                            <div style="text-align:center">
                                <span class="text" v-show="selectPage!=1" @click.stop="prevePage">上一页</span>
                                <span class="text" style="padding-left: 30px;" @click.stop="nextPage"
                                      v-show="selectPage !=pageCount">
									下一页
								</span>
                            </div>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="addForm.adType == 4 || addForm.adType == 6 || addForm.adType == 8"
                                  label="选择活动" prop="selectAct" style="width:800px">
                        <el-select placeholder="请选择活动"
                                   filterable
                                   remote
                                   @visible-change="getSelectList"
                                   @change="getlist"
                                   :disabled="isView"
                                   :remote-method="getSelectList" v-model="valueid" popper-class="selectJob" size="mini">
                            <el-option v-for="item in restoreTable" :key="item.id" :label="item.acTitle"
                                       :value="item.id">
                                <span v-if="item.createUserOrganizationName!=''" style="float: left;width:200px" :title="item.acTitle">{{ item.acTitle+"--"+item.createUserOrganizationName }}</span>
                            </el-option>
                            <div style="text-align:center">
                                <span class="text" v-show="selectPage!=1" @click.stop="prevePage">上一页</span>
                                <span class="text" style="padding-left: 30px;" @click.stop="nextPage"
                                      v-show="selectPage !=pageCount">
									下一页
								</span>
                            </div>
                        </el-select>
                    </el-form-item>
                    <el-form-item v-show="addForm.adType== 9"
                                  label="输入链接" prop="selectAct">
                        <el-input placeholder="请输入链接" :disabled="isView" v-model="value" size="mini" style="width: 40%"></el-input>
                    </el-form-item>
                </div>
                <el-form-item label="开始时间" prop="adBeginTime">
                    <el-date-picker :readonly="isView" @change="checkStartTime" v-model="addForm.adBeginTime" :picker-options="pickerOption"
                                    value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期" size="mini" default-time="00:00:00">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="adEndTime">
                    <el-date-picker size="mini" :readonly="isView" @change="getAddTime" v-model="addForm.adEndTime" :picker-options="pickerOption"
                                    type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" default-time="23:59:59">
                    </el-date-picker>
                </el-form-item>
                <div class="adAccUrl">
                    <el-form-item label="广告图片" required>
                        <el-col :span="12">
                            <el-form-item prop="adAccUrl">
                                <el-input :disabled="isView" readonly @focus="$refs.selFile.open()"
                                          :placeholder="placeholder" v-model="addForm.adAccUrl" size="mini"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col style="width: 40px;height: 40px;overflow: hidden;margin-left: 15px;background: #f5f6f7;text-align: center;">
                            <div class="demo-image__preview">
                                <el-image :src="addForm.adAccUrl" width="40" height="40"
                                          :preview-src-list="addForm.adAccUrl.split(',')">
                                    <div slot="error" class="image-slot">
                                        <i class="el-icon-picture-outline" style="font-size: 20px;"></i>
                                    </div>
                                </el-image>
                            </div>
                        </el-col>
                        <el-col style="width: 90px;margin-left: 15px;">
                            <el-form-item>
                                <el-button :disabled="isView" icon="el-icon-search" type="primary"
                                           @click="$refs.selFile.open()" size="mini">预览
                                </el-button>
                                <selFile ref="selFile" @callback="selFileCallBack" albumCode="pic_root"
                                         dialogTitle="选择图片1" selectType="radio" selMaxWidth="300px"
                                         selMaxHeight="300px"></selFile>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                </div>
            </el-form>
            <span slot="footer" class="dialog-footer">
				<el-button v-if="!isView" type="primary" @click="submitAdvert('addForm')" size="mini" :loading="loadBtn"
                           v-has="'/mall-cloud-advert/poster/addItem'">确 定</el-button>
				<el-button @click="closeDialog" size="mini">取 消</el-button>
			</span>
        </el-dialog>
        <!--        广告冲突提示框-->
        <el-dialog
                title=""
                :visible.sync="dialogVisibleAd"
                width="60%"
                :before-close="handleClose">
            <span style="padding-bottom: 30px;font-size: 20px;font-weight: 600;">该广告创建的时间与以下广告的时间冲突，如果覆盖，请选择覆盖的广告</span>
            <el-radio-group v-model="chooiseAd" @change="changeChooseAd">
                <el-row style="padding: 10px" v-for="(item,index) in conflictAdList" :key="item.conflictAdvertId">
                    <el-radio :label="index">{{item.conflictAdvertName}}
                        冲突的时间:{{item.conflictBeginTime}}到{{item.conflictEndTime}}
                    </el-radio>
                </el-row>
            </el-radio-group>
            <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="sureConflictAd" :loading="chooseLoading">确 定</el-button>
  </span>
        </el-dialog>

        <!--查看-->
        <el-drawer title="查看广告" :visible.sync="dialogTableVisible" :with-header="true" size="50%" :before-close="beforeClose">
            <div style="padding: 30px">
                <avue-form ref="obj" v-model="obj" :option="optionView">
                    <template slot="adAccUrl">
                        <el-row style="display: flex;">
                            <el-input disabled :value="obj.adAccUrl"></el-input>
                            <el-image :src="obj.adAccUrl" style="width: 50px;height: 50px;margin-left: 10px;" :preview-src-list="srcList"></el-image>
                        </el-row>
                    </template>
                    <template slot="adValue">
                        <el-row style="display: flex;">
                            <el-input disabled :value="restoreTable"></el-input>
                        </el-row>
                    </template>
                </avue-form>
            </div>
        </el-drawer>
    </basic-container>
</template>
<script>
    import selFile from "@/components/file/selFile";
    import uploadPic from "@/components/file/uploadPic";
    import {
        getList,
        remove,
        update,
        add,
        getDetail,
        getPosList,
        getGoodsList,
        getStoreList,
        getActList,
        listTreeBylevelM,
        queryConflict,
        listTreeByUserOrganization,
        commodity,
        activity
    } from "@/api/base/operations/advertManage/advert";
    import {
        mapGetters
    } from "vuex";
    import {
        testAccountName
    } from '@/util/util';
    import { validateURL} from '@/util/validate.js';

    var Dict = JSON.parse(localStorage.getItem("mall-dictionary")).content;
    var adPutStatusDict = [{
        label: "是",
        value: true
    }, {
        label: "否",
        value: false
    }];
    export default {
        data() {
            return {
                obj:{},
                dialogTableVisible:false, //查看列表
                dic:[{
                    label:'',
                    value:0
                },{
                    label:'',
                    value:1
                }],
                isAdmin:'',
                userRole:'',
                userId:'',
                userOrganizationId: '',
                pickerOption: {
                    disabledDate(time) {
                        return time.getTime() + 3600 * 1000 * 24 * 1 < Date.now();
                    }
                },
                chooseLoading: false,
                chooseAdIndex: '', // 被选择覆盖广告的index
                chooiseAd: '', //选择覆盖的Ad
                conflictAdList: [],
                dialogVisibleAd: false,
                goodsClassIdsValue: [],
                chooseObj: {},
                propsClass: {
                    label: 'name',
                    id: 'id',
                    children: 'childrenNodes',
                },
                goodsClassIdsOptions: '',
                selectQuery: {},
                acTime: '',
                placeholder: '请选择广告图片',
                value: '',
                valueid:'',
                valueFlag: '',
                total: null, // 获取总数据量
                pageCount: null, // 获取总页数
                selectPage: 1, // 当前页数
                restoreTable: [], //当前页数数据
                firstEdit: false,//是否是第一次打开编辑框
                loadBtn: false,
                srcList: [],
                apPrice: "",
                titleBan: '新增广告',
                isView: false,
                isApView: false,
                posData: [],
                typeData: [],
                editForm: [],
                acStage:3,
                activeName: 'first',
                addForm: {
                    adTitle: "",
                    adApId: "",
                    mark: "",
                    adType: "",
                    adTypeName: '',
                    adTypeValue: "",
                    adBeginTime: "",
                    adEndTime: "",
                    adAccUrl: "",
                    organizationId:'',
                },
                idTitle: '',
                addrules: {
                    adTitle: [{
                        required: true,
                        validator: testAccountName,
                        trigger: "blur"
                    }],
                    adApId: [{
                        required: true,
                        message: "请选择广告位",
                        trigger: "change"
                    }],
                    adBeginTime: [{
                        required: true,
                        message: "请选择开始时间",
                        trigger: "blur"
                    }],
                    adEndTime: [{
                        required: true,
                        message: "请选择结束时间",
                        trigger: "blur"
                    }],
                    adStoreId: [{
                        required: true,
                        message: "请输入商品id",
                        trigger: "blur"
                    }],
                    adAccUrl: [{
                        required: true,
                        message: "请选择广告图片",
                        trigger: "change"
                    }],
                    goodsClassIdsLabel: [{
                        required: this.userRole?false:true,
                        message: "请选择项目可见范围",
                        trigger: "change"
                    }]
                },
                editDialogVisible: false,
                dialogVisible: false,
                form: {},
                query: {},
                queryFlag: false,
                loading: true,
                rolesTree: [],
                rolesKeys: [],
                box: false,
                page: {
                    pageSize: 10,
                    currentPage: 1,
                    total: 0
                },
                option: {
                    size: "mini",
                    excelBtn: false,
                    addBtn: false,
                    tip: false,
                    editBtn: false,
                    delBtn: true,
                    border: true,
                    index: false,
                    selection: false,
                    viewBtn: false,
                    rowKey: "id",
                    height: "auto",
                    // calcHeight: 380,
                    dialogType: "dialog",
                    align: 'center',
                    menuWidth: 180,
                    searchMenuSpan: 6,
                    column: [
                        {
                            label: "广告名称",
                            prop: "adTitle",
                            search: true,
                            fixed: true,
                        },
                        {
                            label: "广告位名",
                            prop: "apTitle",
                            search: true,
                            addDisplay: false,
                            editDisplay: false,
                            rules: [{
                                required: true,
                                message: "请输入广告位",
                                trigger: "blur"
                            }]
                        },
                        {
                            type: "select",
                            label: "广告类型",
                            prop: "adType",
                            dicData: Dict.ADVERT_TYPE,
							filterable:true,
                            rules: [{
                                required: true,
                                message: "请输入广告类型 1商品详情  2店铺  4促销活动 6秒杀活动 8拼团 7聚合页",
                                trigger: "blur"
                            }]
                        },
                        {
                            type: "select",
                            label: "是否投放",
                            prop: "adPutStatus",
                            search: true,
                            dicData: adPutStatusDict,
                            rules: [{
                                required: true,
                                message: "请选择是否投放",
                                trigger: "blur"
                            }]
                        },
                        {
                            type: "date",
                            label: "开始时间",
                            prop: "adBeginTime",
                            width:140,
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            rules: [{
                                required: true,
                                message: "请输入广告开始时间--不可售卖可用",
                                trigger: "blur"
                            }]
                        },
                        {
                            type: "date",
                            label: "结束时间",
                            prop: "adEndTime",
                            width:140,
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            rules: [{
                                required: true,
                                message: "请输入广告结束时间--非售卖广告可用",
                                trigger: "blur"
                            }]
                        },
                        {
                            label: "区域",
                            type: "tree",
                            prop: "organizationId",
                            search: true,
                            defaultExpandAll: false,
                            disabled: true,
                            dicUrl: '/base/organization/listTreeBylevelM?levelM=3',
                            props: {
                                label: 'name',
                                value: 'id',
                                children: 'childrenNodes'
                            },
                            rules: [{
                                required: true,
                                message: "请选择区域",
                                trigger: "blur"
                            }]
                        },
                        {

                            label: "广告状态",
                            prop: "adStatus",
                            type: 'switch',
                            slot: true,
                            cell: true,
                        },
                        {
                            label: "广告图片",
                            type:'img',
                            hide: true,
                            prop: "adAccUrl",
                            display:true,
                            disabled: true,
                            // slot:true,
                            rules: [{
                                required: true,
                                message: "请输入广告图片",
                                trigger: "blur"
                            }]
                        },
                    ]
                },
                optionView: {
                    excelBtn: false,
                    emptyBtn: false,
                    tip: false,
                    editBtn: false,
                    submitBtn:false,
                    delBtn: false,
                    border: true,
                    index: false,
                    selection: false,
                    viewBtn: false,
                    rowKey: "id",
                    height: "auto",
                    // calcHeight: 380,
                    dialogType: "dialog",
                    align: 'center',
                    labelWidth: 130,
                    column: [{
                        label: "广告名称",
                        prop: "adTitle",
                        row: true,
                        disabled:true,
                        span:20
                    },
                        {
                            label: "广告位",
                            prop: "apTitle",
                            row: true,
                            disabled:true,
                            span:20
                        },
                        {
                            type: "select",
                            label: "广告类型",
                            prop: "adType",
                            dicData: Dict.ADVERT_TYPE,
							filterable:true,
                            row: true,
                            disabled:true,
                            span:20
                        },
                        {
                            label:'广告类型值选择',
                            prop: "adValue",
                            formslot: true,
                            disabled:true,
                            row:true,
                            span:20
                        },
                        {
                            type: "datetime",
                            label: "开始时间",
                            prop: "adBeginTime",
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            row: true,
                            disabled:true,
                            span:20
                        },
                        {
                            type: "datetime",
                            label: "结束时间",
                            prop: "adEndTime",
                            format: "yyyy-MM-dd HH:mm:ss",
                            valueFormat: "yyyy-MM-dd HH:mm:ss",
                            row: true,
                            disabled:true,
                            span:20
                        }, {
                            label: "广告图片",
                            prop: "adAccUrl",
                            row: true,
                            disabled:true,
                            formslot:true,
                            span:20
                        }
                    ]
                },
                data: [],
                dicData: [],
                mark: '',
                isSwitch:false,
            };
        },
        created() {
            this.userOrganizationId = this.userInfo.organizationId // 获取用户的区域Id
            // 获取范围数据
            listTreeByUserOrganization().then(res=>{
                this.goodsClassIdsOptions = res.data.data;
            })
            this.userId = this.userInfo.id // 获取用户的区域Id
            // var arr = [12,11]
            var arr = this.userInfo.roleIds
            this.userRole = !arr.includes(1) && !arr.includes(10) && !arr.includes(11) && !arr.includes(8) // 是业务单元
            this.isAdmin = arr.includes(1) || arr.includes(8)
            console.log('userRoles',this.userRole)
            this.dicData = JSON.parse(localStorage.getItem("mall-dictionary")).content;
            this.typeData = this.dicData.ADVERT_TYPE
            console.log(this.dicData.ADVERT_TYPE,'------0000000000')
        },
        watch: {
            dialogVisible(val) {
                if (!val) {
                    this.$nextTick(() => {
                        this.$refs["addForm"].resetFields();
                    })
                    this.loadBtn = false
                }else {
                    listTreeByUserOrganization().then(res=>{
                        this.goodsClassIdsOptions = res.data.data;
                    })
                }
            },
            'addForm.adType'() {
                if (!this.firstEdit) {
                    //重置
                    this.value = "";
                    this.valueFlag = "";
                    this.total = null; // 获取总数据量
                    this.pageCount = null; // 获取总页数
                    this.selectPage = 1; // 当前页数
                    this.restoreTable = []; //当前页数数据
                    this.selectQuery = "";
                }
                if (this.dialogVisible) {
                    this.getSelectList();
                }

            },
        },
        components: {
            selFile,
            uploadPic
        },
        computed: {
            ...mapGetters(["permission", 'userInfo', 'dictionariy']),
            permissionList() {
                return {};
            },
        },
        methods: {
            beforeClose(done) {
                this.dialogTableVisible=false
                this.$refs.obj.resetForm();
                this.$refs.obj.clearValidate();
                this.obj={}
                this.value=''
                if(done) {
                    done()
                }
            },
            handleEdit(row) {
                this.restoreTable=''
                let type = row.adType
                let value = row.adTypeValue
                if(!row.adTypeValue) {
                    this.valueFlag = "";
                    this.selectQuery = "";
                    this.obj = row
                    this.srcList = [row.adAccUrl]
                    this.dialogTableVisible = true
                    return;
                }
                //查询参数
                let param = {};
                //1商品详情  2店铺  4促销活动 6秒杀活动 8拼团
                if (type == 1) {
                    param = {id:value};
                    getGoodsList('','',param).then(res => {
                        this.restoreTable = res.data.data[0].goodsName;
                        this.value = '商品名称'
                    });
                } else if (type == 2) {
                    param = {
                        id:value
                    };
                    getStoreList('','',param).then(res => {
                        console.log(res.data.data[0].storeName,'-----999999999990000000')
                        this.restoreTable = res.data.data[0].storeName;
                        this.value = '店铺名称'
                    });
                } else if (type == 4 || type == 6 || type == 8) {
                    param = {id:value};
                    getActList('','',param).then(res => {
                        this.restoreTable = res.data.data[0].acTitle;
                        this.value = '活动名称'
                    });
                }else if(type==9) {
                    this.restoreTable = row.adTypeValue;
                }
                this.obj = row
                this.srcList = [row.adAccUrl]
                this.dialogTableVisible = true
            },
            // 取消覆盖广告
            handleClose() {
                this.$message({
                    type: "warning",
                    message: "建议修改该广告时间!"
                });
                this.chooseAdIndex = ''
                this.dialogVisibleAd = false
                this.chooiseAd=''
                this.onLoad(this.page,this.params)
            },
            changeChooseAd(value) { // 冲突广告单选框选择
                console.log('value',value)
                this.chooseAdIndex = value
            },
            // 确定覆盖的广告
            sureConflictAd() {
                console.log('chooseAdIndex',this.chooseAdIndex)
                if(this.chooseAdIndex==='') {
                    this.$message({
                        type: "error",
                        message: "请选择要覆盖的广告!"
                    });
                    return
                }
                this.chooseLoading = true
                if(this.value) {
                    this.addForm.adTypeValue = this.value;
                }
                this.addForm.conflictJson = JSON.stringify(this.conflictAdList[this.chooseAdIndex])
                if (this.addForm.id) {
                    update(this.addForm).then((res) => {
                        if (res.data.code == 200) {
                            this.loadBtn = false
                            if(this.isSwitch) {
                                this.$message({
                                    type: "success",
                                    message: "开启成功!"
                                });
                            }else {
                                this.$message({
                                    type: "success",
                                    message: "编辑广告成功,请至广告审核页面进行审核!"
                                });
                            }
                            this.dialogVisible = false;
                            this.dialogVisibleAd = false
                            this.chooseLoading = false
                            this.loadBtn = false
                            this.onLoad(this.page, this.query)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.data.message
                            });
                        }
                        this.chooseLoading = false
                        this.loadBtn = false
                    })
                    this.chooseAdIndex = ''
                    this.addForm = {}
                } else {
                    add(this.addForm).then((res) => {

                        if (res.data.code == 200) {
                            this.loadBtn = false
                            this.$message({
                                type: "success",
                                message: "新增广告成功,请至广告审核页面查看!"
                            });
                            this.dialogVisible = false;
                            this.dialogVisibleAd = false
                            this.chooseLoading = false
                            this.loadBtn = false
                            this.onLoad(this.page, this.query)
                        } else {
                            this.$message({
                                type: "error",
                                message: res.data.message
                            });
                        }
                        this.chooseLoading = false
                        this.loadBtn = false
                    })
                    this.chooseAdIndex = ''
                }
            },
			//删除已选中的所有的
			goodsClassRemove(val) {
				console.log(val)
				this.goodsClassIdsValue = ''
				this.addForm.organizationId = ''
				this.addForm.goodsClassIdsLabel = []
				this.$refs['addForm'].validate((valid) => {

				})
				// this.obj.goodsClassIdsLabel = [];
				// this.$refs.goodsClassTree.setChecked(val, false);
				// let arr = this.$refs.goodsClassTree.getCheckedNodes();
				// for (let i in arr) {
				// 	this.obj.goodsClassIdsLabel.push(arr[i].name);
				// }
			},
            //可见区域选择事件
            signHandleCheckChange(data, node) {
                console.log('signHandleCheckChange', data, node);
                this.goodsClassIdsValue = [data]
                this.addForm.organizationId = data.id
                this.addForm.goodsClassIdsLabel = [data.name]
            },
            getlist(val){
                console.log(val,'-----------00000000000000')
                this.value=val;
            },
            getSelectList(queryFlag, pageFlag) {
                console.log('queryFlag',queryFlag,pageFlag)
                if (queryFlag == false && pageFlag != true) {
                    return;
                }
                if (queryFlag === true || queryFlag == undefined) {
                    this.valueFlag = "";
                    this.selectQuery = "";
                } else {
                    this.valueid = queryFlag
                    // 当搜索词改变时,把page重新赋值为1
                    if(this.selectQuery == queryFlag) {
                        this.selectQuery = queryFlag
                    }else {
                        //商品选择框
                        this.selectPage = 1
                        this.valueFlag = this.value;
                        this.selectQuery = queryFlag;
                    }
                }
                //查询参数
                let param = {};
                /*else{
                    this.value="";
                }*/
                let getListMethod = getGoodsList;
                //1商品详情  2店铺  4促销活动 6秒杀活动 8拼团
                if (this.addForm.adType == 1) {
                    if (this.firstEdit) {
                        param = {id: this.valueFlag};
                        this.firstEdit = false;
                    } else {
                        param = {goodsName: this.selectQuery, goodsStatus: 0};
                        console.log('params',param)
                    }
                } else if (this.addForm.adType == 2) {
                    getListMethod = getStoreList;
                    if (this.firstEdit) {
                        param = {
                            id: this.valueFlag,
                            storeStatus: 2,
                            queryContainDelete:true
                        };
                        this.firstEdit = false;
                    } else {
                        param = {
                            storeName: this.selectQuery,
                            storeStatus: 2, // 需要获取关闭店铺的数据
                            queryContainDelete:''
                        };
                    }
                    if(this.titleBan=='新增广告'){
                        param.queryContainDelete=''
                    }else{
                        param.queryContainDelete=true
                        param.storeStatus=''
                    }
                } else if (this.addForm.adType == 4) {
                    getListMethod = getActList;
                    if (this.firstEdit) {
                        param = {
                            id: this.valueFlag
                        };
                        this.firstEdit = false;
                    } else {
                        param = {acTitle: this.selectQuery, isPromotion: true,acStage:this.acStage};
                    }
                } else if (this.addForm.adType == 6) {
                    getListMethod = getActList;
                    if (this.firstEdit) {
                        param = {
                            id: this.valueFlag
                        };
                        this.firstEdit = false;
                    } else {
                        param = {acTitle: this.selectQuery, acType: 3,acStage:this.acStage};
                    }
                } else if (this.addForm.adType == 8) {
                    getListMethod = getActList;
                    if (this.firstEdit) {
                        param = {
                            id: this.valueFlag
                        };
                        this.firstEdit = false;
                    } else {
                        param = {acTitle: this.selectQuery, acType: 2,acStage:this.acStage};
                    }
                }
                getListMethod(this.selectPage, 10, param).then(res => {
                    this.restoreTable = res.data.data;
                    this.total = res.data.count; // 数据总数量
                    this.pageCount = Math.ceil(this.total / 10); // 因为我每次只请求20条， 所以算出总页数
                    // this.value = this.restoreTable[0].id; // 因为每次都选取第一条数据;
                });
                this.firstEdit = false;
            },
            prevePage() {
                if (this.selectPage > 1) { // 判断点击的页数是否小于1
                    --this.selectPage;
                }
                this.getSelectList(this.selectQuery, true);
            },
            nextPage() {
                if (this.selectPage < this.pageCount) { // 判断点击的页数是否小于总页数;
                    ++this.selectPage;
                    this.getSelectList(this.selectQuery, true);
                }
            },
            checkStartTime() {
                if (this.addForm.adEndTime != null && this.addForm.adEndTime != undefined && this.addForm.adEndTime != "") {
                    if (this.addForm.adBeginTime > this.addForm.adEndTime) {
                        this.$message({
                            type: "error",
                            message: "开始时间不能大于结束时间"
                        });
                        this.addForm.adBeginTime = '';
                        return;
                    }
                }
                if (this.addForm.adBeginTime < new Date().getTime()) {
                    this.$message({
                        type: "error",
                        message: "开始时间不能小于当前时间"
                    });
                    this.addForm.adBeginTime = ''
                }
            },
            getAddTime() {
                if (this.addForm.adBeginTime > this.addForm.adEndTime) {
                    this.$message({
                        type: "error",
                        message: "结束时间不能小于开始时间"
                    });
                    this.addForm.adEndTime = ''
                }
            },
            //选择广告类型
            getAdType(val) {
                if(val) {
                    this.valueid=''
                    console.log(val)
                    for (let obj of this.typeData) {
                        if (obj.value == val) {
                            this.addForm.adTypeName = obj.label;
                            this.addForm.adType = obj.value;
                            if (obj.value == 1) {
                                this.idTitle = '商品'
                            } else if (obj.value == 2) {
                                this.idTitle = '店铺'
                            } else if (obj.value == 4) {
                                this.idTitle = '促销活动'
                            } else if (obj.value == 6) {
                                this.idTitle = '秒杀活动'
                            } else if (obj.value == 8) {
                                this.idTitle = '拼团活动'
                            } else if (obj.value == 7) {
                                this.idTitle = '聚合页'
                            } else if (obj.value == 9){
                                this.idTitle = '自定义链接'
                            }
                        }
                    }
                }
            },
            // 选择图片
            selFileCallBack(obj) {
                this.addForm.adAccUrl = obj[0];
            },
            // 新增按钮
            handleAdd() {
                this.getSelectList();
                this.value=''
                this.titleBan = '新增广告'
                this.isView = false
                this.isApView = false
                this.mark = ''
                this.addForm = {
                    adTitle: "",
                    adApId: "",
                    mark: "",
                    adType: "",
                    adTypeName: '',
                    adTypeValue: "",
                    adBeginTime: "",
                    adEndTime: "",
                    adAccUrl: "",
                    goodsClassIdsLabel:[],
                    organizationId:this.userOrganizationId
                    // deductionOfCharges: "",
                }
                this.$nextTick(() => {
                    this.$refs.addForm.clearValidate();
                })
                this.dialogVisible = true;
                getPosList(1, false).then(res => {
                    if(res.data.code==200) {
                        const data = res.data;
                        console.log(data,'------')
                        if(this.userRole) {
                            this.posData = res.data.data.filter(item=>{
                                return item.apEncoding != 'XT_AP1202837735474900993'
                            })
                        }else {
                            this.posData = data.data
                        }
                    }else {
                        this.$message({
                            type: "error",
                            message: res.data.message
                        });
                    }
                })
            },
            //关闭
            closeDialog() {
                this.dialogVisible = false;
                this.firstEdit = true;
                // this.onLoad(this.page, this.query);
                this.$nextTick(() => {
                    this.$refs.addForm.resetFields();
                    this.$refs.addForm.clearValidate();
                })

            },
            // 提交按钮
            submitAdvert() {
                console.log('this.addForm',this.addForm)
				if(this.addForm.organizationId==''&& !this.userRole ){
					this.$message.error("请选择项目可见范围");
					return
				}
				if(this.addForm.adType==9 && !validateURL(this.value)) {
				    this.$message.error("请输入合法的Url链接");
				    return
				}
                this.$refs['addForm'].validate((valid) => {
                    if (valid) {
                        this.loadBtn = true
                        console.log(this.addForm.adType,this.value,'-----------000000000000')
                        if (this.addForm.adType && !this.value) {
                            if(this.addForm.adType!=9) {
                                this.$message.error("请选择" + this.idTitle);
                            }else {
                                this.$message.error("请输入" + this.idTitle);
                            }
                            this.loadBtn = false;
                            return;
                        }
                        if (this.activeName == 'first') {
                            if (this.addForm.id) {
                                this.addForm.adTypeValue = this.value;
                                console.log('this.addForm', this.addForm)
                                queryConflict(this.addForm).then(res => {
                                    if (res.data.code == 200) {
                                        let key = Object.keys(res.data.data)
                                        if (key == 'toPassConflict') { // 与正在投放中的广告冲突
                                            this.$message({
                                                type: "warning",
                                                message: res.data.data.toPassConflict
                                            });
                                            this.loadBtn = false
                                        } else if (key == 'pass') { //没有广告冲突,直接新增广告冲突成功
                                            update(this.addForm).then((res) => {
                                                if (res.data.code == 200) {
                                                    this.loadBtn = false
                                                    this.$message({
                                                        type: "success",
                                                        message: "编辑广告成功,请至广告审核页面进行审核!"
                                                    });
                                                    this.onLoad(this.page, this.query)
                                                    this.dialogVisible = false;
                                                } else {
                                                    this.$message({
                                                        type: "error",
                                                        message: res.data.message
                                                    });
                                                }
                                            })
                                            this.loadBtn = false
                                        } else if (key == 'toNotPassConflict') { //有未投放的广告冲突
                                            console.log('length', res.data.data.toNotPassConflict.length)
                                            if (res.data.data.toNotPassConflict.length == 1) {
                                                let item = res.data.data.toNotPassConflict[0]
                                                let str=`该广告创建的时间与${item.conflictAdvertName}广告的时间${item.conflictBeginTime}到${item.conflictEndTime}冲突，是否覆盖？`
                                                this.$confirm(str, '提示', {
                                                    confirmButtonText: '确定',
                                                    cancelButtonText: '取消',
                                                    type: 'warning'
                                                }).then(() => {
                                                    this.chooseLoading = true
                                                    this.addForm.adTypeValue = this.value;
                                                    this.addForm.conflictJson = JSON.stringify(item)
                                                    update(this.addForm).then((res) => {
                                                        if (res.data.code == 200) {
                                                            this.loadBtn = false
                                                            this.$message({
                                                                type: "success",
                                                                message: "编辑广告成功,请至广告审核页面进行审核!"
                                                            });
                                                            this.dialogVisible = false;
                                                            this.dialogVisibleAd = false
                                                            this.chooseLoading = false
                                                            this.loadBtn = false
                                                            this.onLoad(this.page, this.query)
                                                        } else {
                                                            this.$message({
                                                                type: "error",
                                                                message: res.data.message
                                                            });
                                                        }
                                                        this.chooseLoading = false
                                                        this.loadBtn = false
                                                    }).catch(() => {
                                                        this.dialogVisibleAd = false
                                                        this.$message({
                                                            type: "warning",
                                                            message: "建议修改新增的广告时间!"
                                                        });
                                                        this.onLoad(this.page,this.params)
                                                    })
                                                })
                                            } else {
                                                this.dialogVisibleAd = true
                                                this.conflictAdList = res.data.data.toNotPassConflict // 冲突广告的列表
                                            }
                                            console.log('aaaa')
                                            this.loadBtn = false
                                        }
                                        this.loadBtn = false
                                    }
                                })

                            } else {
                                this.addForm.adTypeValue = this.value;
                                console.log('this.addForm', this.addForm)
                                queryConflict(this.addForm).then(res => {
                                    if (res.data.code == 200) {
                                        let key = Object.keys(res.data.data)
                                        if (key == 'toPassConflict') { // 与正在投放中的广告冲突
                                            this.$message({
                                                type: "warning",
                                                message: res.data.data.toPassConflict
                                            });
                                            this.loadBtn = false
                                        } else if (key == 'pass') { //没有广告冲突,直接新增广告冲突成功
                                            add(this.addForm).then((res) => {
                                                if (res.data.code == 200) {
                                                    this.loadBtn = false
                                                    this.$message({
                                                        type: "success",
                                                        message: "新增广告成功,请至广告审核页面查看!"
                                                    });
                                                    this.dialogVisible = false;
                                                    this.onLoad(this.page, this.query)
                                                } else {
                                                    this.$message({
                                                        type: "error",
                                                        message: res.data.message
                                                    });
                                                }
                                            })
                                            this.loadBtn = false
                                        } else if (key == 'toNotPassConflict') { //有未投放的广告冲突
                                            let item = res.data.data.toNotPassConflict[0]
                                            let str=`该广告创建的时间与${item.conflictAdvertName}广告的时间${item.conflictBeginTime}到${item.conflictEndTime}冲突，是否覆盖？`
                                            if (res.data.data.toNotPassConflict.length == 1) {
                                                this.$confirm(str, '提示', {
                                                    confirmButtonText: '确定',
                                                    cancelButtonText: '取消',
                                                    type: 'warning'
                                                }).then(() => {
                                                    this.addForm.conflictJson = JSON.stringify(item)
                                                    add(this.addForm).then((res) => {
                                                        if (res.data.code == 200) {
                                                            this.loadBtn = false
                                                            this.$message({
                                                                type: "success",
                                                                message: "新增广告成功,请至广告审核页面查看!"
                                                            });
                                                            this.dialogVisible = false;
                                                            this.dialogVisibleAd = false
                                                            this.chooseLoading = false
                                                            this.loadBtn = false
                                                            this.onLoad(this.page, this.query)
                                                        } else {
                                                            this.$message({
                                                                type: "error",
                                                                message: res.data.message
                                                            });
                                                        }
                                                        this.chooseLoading = false
                                                        this.loadBtn = false
                                                    })
                                                    this.chooseAdIndex = ''
                                                }).catch(() => {
                                                    this.dialogVisibleAd = false
                                                    this.$message({
                                                        type: "warning",
                                                        message: "建议修改新增的广告时间!"
                                                    });
                                                    this.onLoad(this.page,this.params)
                                                });
                                            } else {
                                                this.dialogVisibleAd = true
                                                this.conflictAdList = res.data.data.toNotPassConflict // 冲突广告的列表
                                            }
                                            console.log('aaaa')
                                            this.loadBtn = false

                                        }
                                        this.loadBtn = false
                                    }
                                })

                            }
                        }

                    }

                });
            },
            //获取广告位ID
            getPosData(val) {
                if(!val) return
                //获取
                getDetail(val).then(res => {
                    if (res.status == 200) {
                        this.apPrice = res.data.data.apPrice
                        this.apPrice = res.data.data.apPrice
                        let apWidth = res.data.data.apWidth
                        let apHeight = res.data.data.apHeight
                        this.placeholder = '最佳尺寸 ： ' + apWidth + '像素 x ' + apHeight + '像素'
                        if (res.data.data.mark == 1) {
                            this.mark = '1'
                            this.addForm.mark = '1'
                        } else {
                            this.mark = '2'
                            this.addForm.mark = '2'
                        }
                    }
                })
            },
            // 点击编辑按钮展示对话框
            editFn(row) {
                this.value = row.adTypeValue;
                console.log(this.value,'id------------------')
                this.getSelectList();
                this.firstEdit = true;
                this.titleBan = '编辑广告'
                this.addForm = JSON.parse(JSON.stringify(row))
                this.goodsClassIdsOptions.forEach(item=>{
                    if(item.id==row.organizationId) {
                        console.log('item',item)
                        this.goodsClassIdsValue = [item]
                        this.addForm.organizationId = item.id
                        this.addForm.goodsClassIdsLabel = [item.name]
                    }else {
                        item.childrenNodes.forEach(it=>{
                            if(it.id==row.organizationId) {
                                console.log('it',it)
                                this.goodsClassIdsValue = [it]
                                this.addForm.organizationId = it.id
                                this.addForm.goodsClassIdsLabel = [it.name]
                            }else {
                                it.childrenNodes.forEach(i=>{
                                    if(i.id==row.organizationId) {
                                        console.log('i',i)
                                        this.goodsClassIdsValue = [i]
                                        this.addForm.organizationId = i.id
                                        this.addForm.goodsClassIdsLabel = [i.name]
                                    }
                                })
                            }
                        })
                    }
                })


                console.log(row)
                this.getPosData(row.adApId)
                this.getAdType(row.adType)
                this.isView = false
                this.isApView = true
                this.dialogVisible = true
                //请求下拉列表
                getPosList('', false).then(res => {
                    const data = res.data;
                    this.posData = data.data
                    console.log('over')
                })
                console.log('row',row,this.addForm.adType)
                if(this.addForm.adType==1){
                    commodity(row.adTypeValue).then(res => {
                        console.log(res,'商品id')
                        this.valueid = res.data.data.goodsName;
                    })
                }else if(this.addForm.adType==2){
                    let param = {id:this.value};
                    getStoreList('','',param).then(res => {
                        this.valueid = res.data.data[0].storeName;
                    });
                }else if(this.addForm.adType == 4 || this.addForm.adType == 6 || this.addForm.adType == 8){
                    activity(row.adTypeValue).then(res => {
                        console.log(res,'活动id')
                        this.valueid = res.data.data.acTitle;
                    })
                }
            },
            searchReset() {
                this.query = {};
                this.acTime = []
                this.onLoad(this.page);
            },
            searchChange(params, done) {
                this.page.currentPage = 1
                params.adBeginTime = this.acTime[0] || ''
                params.adEndTime = this.acTime[1] ||''
                console.log(params)
                this.query = params;
                console.log('query',this.query)
                this.onLoad(this.page, params, done);
            },
            currentChange(currentPage) {
                this.page.currentPage = currentPage;
            },
            sizeChange(pageSize) {
                this.page.pageSize = pageSize;
            },
            refreshChange() {
                this.onLoad(this.page);
            },
            onLoad(page, params = {}, done) {
                this.loading = true;
                getList(
                    page.currentPage,
                    page.pageSize,
                    Object.assign(params, this.query)
                ).then(res => {
                    if (done) {
                        done();
                    }
                    if(res.data.data.length<1 && this.page.currentPage>1) {
                        this.page.currentPage -=1
                        this.onLoad(this.page)
                        return
                    }
                    this.loading = false;
                    this.data = res.data.data;
                    this.page.total = res.data.count;
                });
            },
            rowDel(row) {
                this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {
                        return remove(row.id).then(res => {
                            if (res.data.success) {
                                if (this.data.length == 1) {
                                    this.page.currentPage -= 1
                                }
                                this.onLoad(this.page);
                                this.$message({
                                    type: "success",
                                    message: "操作成功!"
                                });
                            } else {
                                this.$message.error(res.data.message);
                            }
                        })
                            .catch(() => {
                                this.$message({
                                    type: 'info',
                                    message: '已取消删除'
                                })
                            })
                    })
            },
            rowSwitchChangeStatus(row) {
                if (row.adStatus != 1) {
					this.$confirm("您关闭广告后，请在'广告审核'中查看", '提示', {
					    confirmButtonText: '确定',
					    cancelButtonText: '取消',
					    type: 'warning'
					}).then(() => {
					    update(row).then(res => {
					        console.log(res)
					        if (res.status == 200) {
					            this.$message({
					                type: "success",
					                message: "关闭成功!"
					            });
					        }
					        this.onLoad(this.page,this.query)
					    })
					}).catch(() => {
					    row.adStatus=1
					})
                    
                } else {
                    console.log('row',row)
                    row.onOrOff = 'on'
                    this.addForm = row
                    queryConflict(row).then(res => {
                        if (res.data.code == 200) {
                            let key = Object.keys(res.data.data)
                            if (key == 'toPassConflict') { // 与正在投放中的广告冲突
                                this.$message({
                                    type: "warning",
                                    message: res.data.data.toPassConflict
                                });
                                row.adStatus=0
                            } else if (key == 'pass') { //没有广告冲突,直接新增广告冲突成功
                                update(row).then((res) => {
                                    if (res.data.code == 200) {
                                        this.loadBtn = false
                                        this.$message({
                                            type: "success",
                                            message: "开启成功!"
                                        });
                                        this.onLoad(this.page, this.query)
                                        this.dialogVisible = false;
                                    } else {
                                        this.$message({
                                            type: "error",
                                            message: res.data.message
                                        });
                                        row.adStatus=0
                                    }
                                })
                                this.loadBtn = false
                            } else if (key == 'toNotPassConflict') { //有未投放的广告冲突
                                console.log('length', res.data.data.toNotPassConflict.length)
                                if (res.data.data.toNotPassConflict.length == 1) {
                                    let item = res.data.data.toNotPassConflict[0]
                                    let str=`该广告创建的时间与${item.conflictAdvertName}广告的时间${item.conflictBeginTime}到${item.conflictEndTime}冲突，是否覆盖？`
                                    this.$confirm(str, '提示', {
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        type: 'warning'
                                    }).then(() => {
                                        this.addForm.adTypeValue = this.value;
                                        this.addForm.conflictJson = JSON.stringify(item)
                                        update(row).then((res) => {
                                            if (res.data.code == 200) {
                                                this.loadBtn = false
                                                this.$message({
                                                    type: "success",
                                                    message: "开启成功!"
                                                });
                                                this.onLoad(this.page, this.query)
                                            } else {
                                                this.$message({
                                                    type: "error",
                                                    message: res.data.message
                                                });
                                            }
                                        })
                                    }).catch(() => {
                                        console.log('取消')
                                        this.dialogVisibleAd = false
                                        this.$message({
                                            type: "warning",
                                            message: "建议修改广告时间!"
                                        });
                                        this.onLoad(this.page,this.params)
                                    })
                                } else {
                                    this.isSwitch = true
                                    this.dialogVisibleAd = true
                                    this.conflictAdList = res.data.data.toNotPassConflict // 冲突广告的列表
                                    console.log('冲突列表',this.conflictAdList)
                                }
                            }
                        }
                    })
                }
            },
        }
    };
</script>

<style lang="scss" scoped>
    .selectJob span {
        width: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .selectJob .text {
        padding-left: 10px;
        font-size: 14px;
        font-weight: bold;
        cursor: pointer;
        color: cornflowerblue;
    }

    .el-table__row .cell > span > span {
        height: 24px;
        display: block;
        overflow: hidden;
        display: -webkit-box;
        text-overflow: ellipsis;
        overflow: hidden;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
    }
    .select{
        height: auto;
        max-height: 120px;
        overflow: auto;
    }
    .el-popper[x-placement^=top]{
        height: auto;
        max-height: 100%;
        margin-bottom: 12px;
    }
</style>
